package com.heima.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.crm.common.contents.CommonMessageContent;
import com.heima.crm.common.result.PageResult;
import com.heima.crm.common.result.Result;
import com.heima.crm.common.utils.BaseContext;
import com.heima.crm.mapper.CrUserMapper;
import com.heima.crm.mapper.DeptMapper;
import com.heima.crm.pojos.dtos.DeptDTO;
import com.heima.crm.pojos.entity.SysDept;
import com.heima.crm.pojos.entity.TbUser;
import com.heima.crm.pojos.vos.DeptDataVo;
import com.heima.crm.pojos.vos.UserDataVo;
import com.heima.crm.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
//@Transactional
@Slf4j
public class DeptServiceImpl extends ServiceImpl<DeptMapper, SysDept> implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private CrUserMapper crUserMapper;


    /**
     * 动态模糊分页查询部门管理
     *
     * @param deptDTO
     * @return
     */
    @Override
    public PageResult deptPageList(DeptDTO deptDTO) {

        //参数校验
        if (deptDTO == null) {
            throw new RuntimeException("数据不存在");
        }
        Integer page1 = deptDTO.getPage();
        Integer size = deptDTO.getSize();
        if (page1 == null && size == null) {
            page1 = 1;
            size = 10;
        }
        //创建一个Lambda对象
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();

        //然后判断对象是否为空,如果不为空就进行模糊查询
        if (deptDTO.getDeptName() != null && deptDTO.getDeptName() != "") {
            lqw.like(SysDept::getDeptName, deptDTO.getDeptName());
        }

        //状态查询
        if (deptDTO.getStatus() != null) {
            lqw.eq(SysDept::getStatus, deptDTO.getStatus());
        }

        //然后在进行倒序排序
        lqw.orderByDesc(SysDept::getCreateTime);

        //现在去构造一个分页查询的对象
        IPage<SysDept> page = new Page<>(page1, size);
        page = page(page, lqw);

        List<SysDept> records = page.getRecords();


        //集团数据
        List<SysDept> groupDepts = records.stream().filter(s -> s.getType() == 0).collect(Collectors.toList());


        if (groupDepts.size()>0){
            for (SysDept groupDept : groupDepts) {
                //所有子公司
                List<SysDept> firmList  = deptMapper.selectList(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId, groupDept.getId()));
                groupDept.setChildren(firmList);

                if (firmList.size()>0){
                    for (SysDept sysDept : firmList) {
                        List<SysDept> deptList = deptMapper.selectList(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId, sysDept.getId()));
                        sysDept.setChildren(deptList);
                    }
                }
            }

            page.setRecords(groupDepts);

            PageResult pageResult = new PageResult(page.getTotal(),page.getRecords());

            return   pageResult;
        }
        List<SysDept> firmDepts = records.stream().filter(s -> s.getType() == 1).collect(Collectors.toList());

        if (firmDepts.size()>0){
                for (SysDept firmDept : firmDepts) {
                    List<SysDept> deptList = deptMapper.selectList(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId, firmDept.getId()));
                    firmDept.setChildren(deptList);
                }
                page.setRecords(firmDepts);
        }

        PageResult pageResult = new PageResult(page.getTotal(),page.getRecords());

        return pageResult;
    }


    /**
     * 添加部门
     *
     * @param sysDept
     * @return
     */
    @Override
    public Result addDept(SysDept sysDept) {

        //校验参数
        if (sysDept == null) {
            throw new RuntimeException("数据不存在");
        }


        SysDept deptVO1 = deptMapper.selectOne(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDeptName, sysDept.getDeptName()));
        if (deptVO1 != null) {
            return Result.error(CommonMessageContent.ALREADY_EXISTS);
        }

        Long currentId = BaseContext.getCurrentId();
        TbUser tbUser = crUserMapper.selectById(currentId);

        sysDept.setStatus(0);
        sysDept.setCreateTime(new Date());
        sysDept.setCreateUser(tbUser.getUserName());
        sysDept.setUpdateTime(new Date());
        sysDept.setUpdateUser(tbUser.getUserName());

        deptMapper.insert(sysDept);
        return Result.success("部门添加成功");
    }

    /**
     * 修改部门
     *
     * @param sysDept
     * @return
     */
    @Override
    public Result updateDept(SysDept sysDept) {

        //参数校验
        if (sysDept == null) {
            throw new RuntimeException("数据不存在");
        }
        SysDept sysDept1 = deptMapper.selectOne(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDeptName, sysDept.getDeptName()).ne(SysDept::getId, sysDept.getId()));
        if (sysDept1 != null) {
            return Result.error(CommonMessageContent.ALREADY_EXISTS);
        }
        deptMapper.updateById(sysDept);
        return Result.success("部门修改成功");
    }

    @Override
    public Result delDept(Long id) {

        //校验参数
        if (id == null) {
            throw new RuntimeException("数据不存在");
        }

        SysDept sysDept = deptMapper.selectById(id);

        //判断该部门是否有连接旗下的子公司或部门,如果有,需删除旗下的子公司或者部门在删除,如果没有可直接删除
        if (sysDept == null) {
            return Result.error(CommonMessageContent.DELETE_ERROR);
        }

        //判断该部门是否是在启用中,如果在启用就不能删除,没启用就删除   ----0启用  1  停用
        if (sysDept.getStatus() == 0) {
            return Result.error(CommonMessageContent.DELETE_ERROR);
        }

        //删除
        deptMapper.deleteById(id);
        return Result.success("删除成功");
    }

    /**
     * 查询所有的部门
     *
     * @return
     */
    @Override
    public Result findDept() {
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            return Result.error(CommonMessageContent.INVALID_PARAMETER);
        }
        TbUser tbUser = crUserMapper.selectById(currentId);
        SysDept sysDept = deptMapper.selectById(tbUser.getDeptId());
        SysDept parentDept = deptMapper.selectOne(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getId, sysDept.getParentId()));

        List<DeptDataVo> list = new ArrayList<>();
        List<SysDept> sysDepts = deptMapper.selectList(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId, parentDept.getId()));
        for (SysDept dept : sysDepts) {
            DeptDataVo deptDataVo = new DeptDataVo();
            deptDataVo.setDeptId(dept.getId());
            deptDataVo.setDeptName(dept.getDeptName());
            list.add(deptDataVo);
        }
        return Result.success(list);
        /*List<SysDept> sysDepts = deptMapper.selectList(null);
        return Result.success(sysDepts);*/
    }

    /**
     * 根据部门id查询所有的用户
     *
     * @param deptId
     * @return
     */
    @Override
    public Result findUser(Long deptId) {

        List<TbUser> users = crUserMapper.selectList(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getDeptId, deptId));

        List<UserDataVo> list = new ArrayList<>();

        for (TbUser user : users) {
            UserDataVo userDataVo = new UserDataVo();
            userDataVo.setUserId(user.getUserId());
            userDataVo.setUserName(user.getUserName());
            list.add(userDataVo);
        }
        return Result.success(list);
    }

    /**
     * 部门启停
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result startOrStop(Integer status, Long id) {
        SysDept sysDept = deptMapper.selectById(id);
        sysDept.setStatus(status);
        deptMapper.updateById(sysDept);
        return Result.success("成功");
    }

    /**
     * 部门修改数据回显
     *
     * @param id
     * @return
     */
    @Override
    public SysDept selectById(Long id) {
        SysDept sysDept = deptMapper.selectById(id);
        return sysDept;
    }


}
